<template>
  <div>
    <el-table :class="[single && 'wms-table', showRowClick && 'table-click']" v-loading="loading" ref="tableRef" stripe
      :data="dataList" @row-click="handleRowClick" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" v-if="showSelection" />
      <el-table-column v-for="(column, index) in columns" :label="column.type ? '操作' : column.label" align="center"
        :prop="column.prop" :width="column.width || ''" :fixed="column.fixed || false"
        :show-overflow-tooltip="column.showOverflow || false" :key="index">
        <template #header="scope" v-if="columnResize">
          <div class="header-cell">
            {{ scope.column.label }}
            <div class="resize-handle" @mousedown="startResize(index, $event)"></div>
          </div>
        </template>
        <template v-if="Object.keys(dictsMapping).includes(column.prop)" #default="scope">
          <dict-tag v-if="showDic(column)" :options="dicts[dictsMapping[column.prop]].value"
            :value="scope.row[column.prop]" />
          <span v-else>{{ scope.row[column.prop] }}</span>
        </template>
        <template v-else-if="column.prop === 'createDate' || column.prop === 'updateDate'" #default="scope">
          <span>{{
            parseTime(scope.row[column.prop], "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
        <template v-else-if="column.prop === 'operate'" #default="scope">
          <el-button v-if="column.type.split(';').includes('detail')" link type="primary" icon="search"
            @click.stop="openDetail(scope.row)">查看</el-button>
          <el-button v-if="column.type.split(';').includes('edit')" link type="primary" icon="edit"
            @click.stop="emit('edit', scope.row)">编辑</el-button>
          <el-button v-if="column.type.split(';').includes('delete')" link type="primary" icon="delete"
            @click.stop="emit('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>
    <div ref="resizeIndicator" class="resize-indicator"></div>
    <pagination v-show="pageInfo.total > 0" :total="pageInfo.total" v-model:page="pageInfo.pageNum"
      v-model:limit="pageInfo.pageSize" @pagination="emit('get-list')" />

    <!-- 点击查看详情信息弹窗 -->
    <table-detail v-model="dialogVisible" :row-data="currentItem" :column-data="detailColumn" :line="line"
      :dicts="dicts" :dictsMapping="dictsMapping" />
  </div>
</template>

<script setup>

import { reactive, ref, useAttrs, computed, getCurrentInstance } from 'vue'
import TableDetail from "@/components/TableDetail/index.vue";
import { useTableDetail } from '@/hooks/tableDetail.js'
// 字典以及字典对应关系
import { dicts, dictsMapping } from './index.js';
const attrs = useAttrs()
const instance = getCurrentInstance()
const showSelection = computed(() => !!instance.vnode.props.onSelectionChange)
const showRowClick = computed(() => !!instance.vnode.props.onRowClick)
const props = defineProps({
  dataList: {
    type: Array,
    require: true,
    default: () => []
  },
  column: {
    type: Array,
    require: true,
    default: () => []
  },
  pageInfo: {
    type: Object,
    require: true,
    default: { total: 0, pageNum: 10, pageSize: 1 }
  },
  loading: {
    type: Boolean,
    default: false
  },
  columnResize: {
    type: Boolean,
    default: false
  },
  line: {
    type: Number,
    default: 2
  },
  single: {
    type: Boolean,
    default: false
  },

})
const showDic = (column) => {
  const dict = dicts[dictsMapping[column.prop]]
  return dict.value && dict.value.length
}
// 添加事件
const emit = defineEmits(['get-list', 'edit', 'delete', 'row-click', 'selection-change'])
const { dialogVisible, currentItem, openDetail, detailColumn } = useTableDetail(props.column)
const columns = reactive(props.column)


const handleRowClick = (row, column, event) => {
  // 检查是否有选中的文本（复制操作）
  const selection = window.getSelection();
  if (selection.toString().length > 0) {
    return;
  }

  emit('row-click', row)
}
const tableRowClassName = (row) => {
  console.log(row, 'lll');

}
const tableRef = ref()
const currentSelect = ref(null)
// feat: 支持单选
function handleSelectionChange(selection) {
  if (!props.single) {
    emit('selection-change', selection)
    return
  }
  if (selection.length > 1) {
    const lastSelected = selection[selection.length - 1];
    tableRef.value.clearSelection();

    nextTick(() => {
      tableRef.value.toggleRowSelection(lastSelected, true);
    });
    currentSelect.value = lastSelected;
  } else {
    currentSelect.value = selection[0] || null;
  }
  emit('selection-change', currentSelect.value)
}

/* 表头拖拽功能 start */

let resizeIndicator = ref(null)
let activeIndex = ref(null)
let startX = ref(0)
let startWidth = ref(0)
// 开始调整列宽
const startResize = (index, event) => {
  event.preventDefault()
  activeIndex.value = index
  startX.value = event.clientX
  startWidth.value = columns[index].width
  // 显示拖拽指示线
  resizeIndicator.value.classList.add('active')
  resizeIndicator.value.style.left = `${event.clientX}px`
  // 添加事件监听
  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
}

// 处理列宽调整
const handleResize = (event) => {
  if (activeIndex.value === null) return
  const currentX = event.clientX
  const deltaX = currentX - startX.value
  const newWidth = Math.max(columns[activeIndex.value].minWidth, startWidth.value + deltaX)
  // 更新指示线位置
  resizeIndicator.value.style.left = `${currentX}px`

  // 更新列宽（实际应用中可能会节流）
  columns[activeIndex.value].width = newWidth
}
// 停止调整列宽
const stopResize = () => {
  activeIndex.value = null
  resizeIndicator.value.classList.remove('active')
  // 移除事件监听
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
}

/*  表头拖拽功能end  */

</script>

<style scoped lang='scss'>
.wms-table {
  :deep(.el-table__header-wrapper .el-checkbox) {
    display: none;
  }
}

.resize-handle {
  position: absolute;
  top: 0;
  right: 0;
  width: 6px;
  height: 100%;
  background: transparent;
  cursor: col-resize;
  z-index: 10;
}

.resize-handle:hover,
.resize-handle.active {
  background: #409EFF;
}

.resize-indicator {
  position: fixed;
  top: 0;
  height: 100vh;
  width: 2px;
  background: #409EFF;
  z-index: 2000;
  pointer-events: none;
  display: none;
}

.resize-indicator.active {
  display: block;
}
</style>